package com.ly.hotel.spainterface.pp.activity;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.core.content.ContextCompat;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.ly.hotel.R;
import com.ly.hotel.common.MyApplication;
import com.ly.hotel.spainterface.jxd.bean.MachineBean;
import com.ly.hotel.spainterface.jxd.utils.MachineUtils;
import com.ly.hotel.spainterface.pp.adapter.PpItemAdapter;
import com.ly.hotel.spainterface.pp.adapter.PpJSListAdapter;
import com.ly.hotel.spainterface.pp.bean.PpJSPluginBean;
import com.ly.hotel.spainterface.pp.bean.PreItemBean;
import com.ly.hotel.spainterface.pp.bean.PreItemIntroBean;
import com.ly.hotel.spainterface.pp.bean.PreItemReturnBean;
import com.ly.hotel.spainterface.pp.bean.PreJSDataBean;
import com.ly.hotel.spainterface.pp.bean.PreJSDataReturnBean;
import com.ly.hotel.spainterface.pp.utils.CommonHttpUtils;
import com.ly.hotel.spainterface.pp.utils.GsonUtils;
import com.ly.hotel.spainterface.pp.utils.PPXmlParseUtils;
import com.ly.hotel.spainterface.pp.view.CommentCustomToast;
import com.ly.hotel.spainterface.pp.view.PpArrangeDialog;
import com.ly.hotel.spainterface.pp.view.PpJSDetailsDialog;
import com.ly.hotel.spainterface.pp.view.PpJSSearchDialog;
import com.ly.hotel.util.ImageUtil;
import com.ly.hotel.util.ProcessWaitingUtil;
import com.ly.hotel.view.TitleLayout;
import com.ly.hotel.view.common.BaseActivity;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by mo on 2018/5/25.
 */

public class PPJSActivity extends BaseActivity {

    private final String TAG = "PPJSActivity";
    private final int TECHNICIAN_ITEM = 0;
    private final int TECHNICIAN_DATA = 1;
    private final int ITEM_INTRO_FILE = 2;
    private ListView jsCategoryListview;
    private RelativeLayout jsCategoryMoreDown;
    private MachineBean machineBean;
    private PpJSPluginBean ppJSPluginBean;
    private Gson gson = new Gson();
    private ImageView itemImg;
    private ScrollView scrollView;
    private TextView itemMsg;
    private TextView itemIntroTitle;
    private TextView itemIntroContent;
    private TextView itemTabooTitle;
    private TextView itemTabooContent;
    private String itemName;
    private boolean isFirstLoad = true;// 是否第一次加载项目文档
    private List<PreItemIntroBean> preItemIntroBeans = new ArrayList<>();
    private Button arrangeItem;
    private LinearLayout itemIntroLayout;
    private GridView jsListGridview;
    private RelativeLayout jsListDownMore;
    private RelativeLayout searchJsLayout;
    private ImageButton searchJS;
    private int itemId;
    private LinearLayout jsListLayout;
    private RadioGroup sexSelect;
    private RadioButton femaleSelect;
    private RadioButton maleSelect;
    private RadioButton allSelect;
    private int sexNum = -1;// 默认选中全部
    private PpJSListAdapter ppJSListAdapter;
    private List<PreJSDataBean> preJSDataBeans;
    private List<PreJSDataBean> tempPreJSDataBean = new ArrayList<>();
    private RelativeLayout jsStatusTips;
    private boolean isFirstGetTechnician = true;// 是否第一次请求技师数据；
    private List<PreItemBean> itemBeans;
    private MyHandler handler = new MyHandler(this);

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.pp_js_activity);
        initView();
        getPluginConfig();
        getMachineInfo();
        getTechnicianItem();
        setArrangeItem();
        setSearchDialog();
    }

    private void initView() {
        TitleLayout titleLayout = findViewById(R.id.title_layout);
        TextView titleName = titleLayout.findViewById(R.id.activity_name);
        titleName.setTextColor(ContextCompat.getColor(this,R.color.mainWhite));
        titleName.setText(getResources().getString(R.string.naviJishiName));

        jsCategoryListview = findViewById(R.id.js_category_listview);
        jsCategoryMoreDown = findViewById(R.id.js_category_more_down);
        itemIntroLayout = findViewById(R.id.item_intro_layout);
        itemImg = findViewById(R.id.item_img);
        scrollView = findViewById(R.id.scroll_view);
        itemMsg = findViewById(R.id.item_msg);
        itemIntroTitle = findViewById(R.id.item_intro_title);
        itemIntroContent = findViewById(R.id.item_intro_content);
        itemTabooTitle = findViewById(R.id.item_taboo_title);
        itemTabooContent = findViewById(R.id.item_taboo_content);
        arrangeItem = findViewById(R.id.arrange_item);

        jsListLayout = findViewById(R.id.js_list_layout);
        jsListGridview = findViewById(R.id.js_list_gridview);
        jsListDownMore = findViewById(R.id.js_list_down_more);

        sexSelect = findViewById(R.id.sex_select);
        femaleSelect = findViewById(R.id.female_select);
        maleSelect = findViewById(R.id.male_select);
        allSelect = findViewById(R.id.all_select);
        sexSelect.setOnCheckedChangeListener(new PpSexRadioGroupListener());
        jsStatusTips = findViewById(R.id.js_status_tips);

        searchJsLayout = findViewById(R.id.search_js_layout);
        searchJS = findViewById(R.id.search_js);
    }

    // 获取插件配置
    private void getPluginConfig(){
        ppJSPluginBean = PPXmlParseUtils.getInstance().parsePpJSPlugin(MyApplication.pluginCfg,MyApplication.interfaceVersion);
    }

    // 获取本机IP、Port、mac地址、电视类别、位置号
    private void getMachineInfo(){
        machineBean = MachineUtils.getHostAndTvInfo();
    }

    // 请求技师项目类别
    private void getTechnicianItem(){
        if(ppJSPluginBean != null){
            if(!TextUtils.isEmpty(ppJSPluginBean.getIp()) && !TextUtils.isEmpty(ppJSPluginBean.getPort())){
                ProcessWaitingUtil.showProcessDialog(this,getResources().getString(R.string.loading_tips),10000);
                String URL = "http://" + ppJSPluginBean.getIp() + ":" + ppJSPluginBean.getPort() + "/api/tech-category.json";
                String request = null;
                CommonHttpUtils.getResource(URL,request,handler,TECHNICIAN_ITEM);
            }else {
                CommentCustomToast.makeText(this,"ip或port插件配置为空！",Toast.LENGTH_SHORT,false).show();
            }
        }else {
            CommentCustomToast.makeText(this,"插件配置出错！",Toast.LENGTH_SHORT,false).show();
        }
    }

    // 请求技师数据
    private void getTechnicianData(){
        ProcessWaitingUtil.showProcessDialog(this,getResources().getString(R.string.loading_tips),10000);
        String URL = "http://" + ppJSPluginBean.getIp() + ":" + ppJSPluginBean.getPort() + "/api/technician.json";
        String request = null;
        CommonHttpUtils.getResource(URL,request,handler,TECHNICIAN_DATA);
    }

    // 加载项目介绍xml文档
    private void getItemIntroFile(){
        ProcessWaitingUtil.showProcessDialog(this,getResources().getString(R.string.loading_tips),10000);
        String URL = "http://" + ppJSPluginBean.getIp() + ":" + ppJSPluginBean.getPort() + "/upload/interface/intro/introCN.xml";
        String request = null;
        CommonHttpUtils.getResource(URL,request,handler,ITEM_INTRO_FILE);
    }

    class PpSexRadioGroupListener implements RadioGroup.OnCheckedChangeListener{

        @Override
        public void onCheckedChanged(RadioGroup group, int checkedId) {
            switch (checkedId){
                case R.id.female_select:
                    sexNum = 0;
                    setTechnicianList();
                    break;

                case R.id.male_select:
                    sexNum = 1;
                    setTechnicianList();
                    break;

                case R.id.all_select:
                    sexNum = -1;
                    setTechnicianList();
                    break;

                default:
                    break;
            }
        }
    }

    // 设置技师类型
    private void setTechnicianItemAdapter(){
        if(itemBeans.size() == 0){
            CommentCustomToast.makeText(this,"后台没配置技师类型！",Toast.LENGTH_SHORT,false).show();
        }else {
            final PpItemAdapter itemAdapter = new PpItemAdapter(this,itemBeans);
            jsCategoryListview.setAdapter(itemAdapter);
            jsCategoryListview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    itemAdapter.setDefaultPosition(position);
                    PreItemBean itemBean = itemBeans.get(position);
                    itemName = itemBean.getName();// 项目名称
                    itemId = itemBean.getId();// 项目ID
                    if(!TextUtils.isEmpty(ppJSPluginBean.getMode())){
                        itemIntroLayout.setVisibility(View.VISIBLE);
                        if(isFirstLoad){
                            isFirstLoad = false;
                            if(ppJSPluginBean.getMode().equals("1")){
                                arrangeItem.setVisibility(View.VISIBLE);
                                getItemIntroFile();
                            }else {
                                getItemIntroFile();
                            }
                        }else {
                            setItemIntro();
                        }
                    }else {
                        itemIntroLayout.setVisibility(View.GONE);
                        jsListLayout.setVisibility(View.VISIBLE);
                        searchJsLayout.setVisibility(View.VISIBLE);
                        if(isFirstGetTechnician){
                            isFirstGetTechnician = false;
                            getTechnicianData();
                        }else {
                            setTechnicianList();
                        }
                    }
                }
            });
            jsCategoryListview.performItemClick(jsCategoryListview.getChildAt(0),0,
                    jsCategoryListview.getItemIdAtPosition(0));

            jsCategoryListview.setOnScrollListener(new AbsListView.OnScrollListener() {
                @Override
                public void onScrollStateChanged(AbsListView view, int scrollState) {

                }

                @Override
                public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
                    if((firstVisibleItem == 0 && visibleItemCount == totalItemCount) || firstVisibleItem > 0 && firstVisibleItem + visibleItemCount == totalItemCount){
                        jsCategoryMoreDown.setVisibility(View.GONE);
                    }else{
                        jsCategoryMoreDown.setVisibility(View.VISIBLE);
                    }
                }
            });
        }
    }

    // 设置技师列表
    private void setTechnicianList(){
        if(preJSDataBeans == null){
            jsStatusTips.setVisibility(View.GONE);
            CommentCustomToast.makeText(PPJSActivity.this,"技师列表为空，请在后台添加！",
                    Toast.LENGTH_SHORT,false).show();
            if(ppJSListAdapter != null){
                ppJSListAdapter.notifyDataSetChanged();
            }
        }else {
            // 筛选不同项目的技师
            tempPreJSDataBean.clear();
            for(int i = 0;i < preJSDataBeans.size();i ++){
                PreJSDataBean preJSDataBean = preJSDataBeans.get(i);
                if(itemId == preJSDataBean.getCid()){
                    if(sexNum != -1){
                        if(sexNum == preJSDataBean.getSex()){
                            tempPreJSDataBean.add(preJSDataBean);
                        }
                    }else {
                        tempPreJSDataBean.add(preJSDataBean);
                    }
                }
            }

            if(tempPreJSDataBean.size() == 0){
                jsStatusTips.setVisibility(View.VISIBLE);
                if(ppJSListAdapter != null){
                    ppJSListAdapter.notifyDataSetChanged();
                }
            }else {
                jsStatusTips.setVisibility(View.GONE);
                ppJSListAdapter = new PpJSListAdapter(this,tempPreJSDataBean);
                jsListGridview.setAdapter(ppJSListAdapter);
                jsListGridview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                        PreJSDataBean preJSDataBean = tempPreJSDataBean.get(position);
                        PpJSDetailsDialog ppJSDetailsDialog = new PpJSDetailsDialog(PPJSActivity.this,R.style.introDialog);
                        ppJSDetailsDialog.setPreJSDataBean(preJSDataBean);
                        ppJSDetailsDialog.setItemName(itemName);
                        if(ppJSPluginBean.isShowCall()){
                            ppJSDetailsDialog.setShowCall(true);
                        }
                        ppJSDetailsDialog.setCanceledOnTouchOutside(false);
                        ppJSDetailsDialog.show();
                    }
                });

                jsListGridview.setOnScrollListener(new AbsListView.OnScrollListener() {
                    @Override
                    public void onScrollStateChanged(AbsListView view, int scrollState) {

                    }

                    @Override
                    public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
                        if((firstVisibleItem == 0 && visibleItemCount == totalItemCount) ||
                                firstVisibleItem > 0 && firstVisibleItem + visibleItemCount == totalItemCount){
                            jsListDownMore.setVisibility(View.GONE);
                        }else{
                            jsListDownMore.setVisibility(View.VISIBLE);
                        }
                    }
                });
            }
        }
    }

    private void setItemIntro(){
        clearContent();
        if(preItemIntroBeans.size() > 0){
            boolean isConfigureItemName = false;
            itemMsg.setText(itemName);
            for(int i = 0;i < preItemIntroBeans.size();i ++){
                PreItemIntroBean preItemIntroBean = preItemIntroBeans.get(i);
                if(itemName.equals(preItemIntroBean.getIname())){
                    isConfigureItemName = true;
                    if(! TextUtils.isEmpty(preItemIntroBean.getIcode())){
                        String imageUrl = MyApplication.getHostResUrl() + "/upload/interface/intro/pic/" +
                                preItemIntroBean.getIcode() + ".jpg";
                        ImageUtil.displayImage_Round(this,imageUrl,itemImg,0);
                    }

                    if(! TextUtils.isEmpty(preItemIntroBean.getIntro())){
                        itemIntroTitle.setText(getString(R.string.js_item_intro) + ":");
                        itemIntroContent.setText(replaceBlank(preItemIntroBean.getIntro()).replace("#","\n"));
                    }

                    if( !TextUtils.isEmpty(preItemIntroBean.getTaboo())){
                        itemTabooTitle.setText(getString(R.string.js_item_taboo) + ":");
                        itemTabooContent.setText(replaceBlank(preItemIntroBean.getTaboo()).replace("#","\n"));
                    }
                    break;
                }
            }
            if(! isConfigureItemName){
                //CommentCustomToast.makeText(this,"项目介绍文档中没有配置" + itemName,Toast.LENGTH_LONG,false).show();
                String imageUrl = MyApplication.getHostResUrl() + "/upload/interface/intro/pic/" +
                        "default.jpg";
                ImageUtil.displayImage_Round(this,imageUrl,itemImg,0);
            }
        }else{
            CommentCustomToast.makeText(this,"没配置项目介绍文档",Toast.LENGTH_LONG,false).show();
        }
    }

    private String replaceBlank(String str){
        String dest = "";
        if (str!=null) {
            Pattern p = Pattern.compile("\\s*|\t|\r|\n");
            Matcher m = p.matcher(str);
            dest = m.replaceAll("");
        }
        return dest;
    }

    private void clearContent(){
        itemMsg.setText("");
        itemIntroTitle.setText("");
        itemIntroContent.setText("");
        itemTabooTitle.setText("");
        itemTabooContent.setText("");
        scrollView.scrollTo(0,0);
    }

    // 安排项目
    private void setArrangeItem(){
        arrangeItem.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                PpArrangeDialog confirmDialog = new PpArrangeDialog(PPJSActivity.this,R.style.introDialog);
                confirmDialog.setItemName(itemName);
                confirmDialog.setMachineBean(machineBean);
                confirmDialog.setPpJSPluginBean(ppJSPluginBean);
                confirmDialog.setCanceledOnTouchOutside(false);
                confirmDialog.show();
            }
        });
    }

    private void setSearchDialog() {
        searchJS.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                PpJSSearchDialog ppJSSearchDialog = new PpJSSearchDialog(PPJSActivity.this,R.style.introDialog);
                ppJSSearchDialog.setItemBeans(itemBeans);
                ppJSSearchDialog.setPreJSDataBeans(preJSDataBeans);
                if(ppJSPluginBean.isShowCall()){
                    ppJSSearchDialog.setShowCall(true);
                }
                ppJSSearchDialog.setCanceledOnTouchOutside(false);
                ppJSSearchDialog.show();
            }
        });
    }

    private class MyHandler extends Handler{

        private WeakReference<PPJSActivity> wrActivity;

        public MyHandler(PPJSActivity ppJSActivity){
            wrActivity = new WeakReference<PPJSActivity>(ppJSActivity);
        }

        @Override
        public void handleMessage(Message msg) {
            PPJSActivity mActivity = wrActivity.get();
            if(mActivity != null){
                switch (msg.what){
                    case 1:
                        ProcessWaitingUtil.closeProcessDialog();
                        String resultString = msg.obj.toString();
                        Log.i(TAG,"接口返回：" + resultString);
                        if(msg.arg1 == TECHNICIAN_ITEM){
                            PreItemReturnBean itemReturnBean = GsonUtils.parseSimpleJson(resultString,
                                    PreItemReturnBean.class);
                            if(itemReturnBean.getCode() == 200){
                                itemBeans = gson.fromJson(itemReturnBean.getData(),
                                        new TypeToken<List<PreItemBean>>(){}.getType());
                                setTechnicianItemAdapter();
                            }
                        }else if (msg.arg1 == ITEM_INTRO_FILE){
                            preItemIntroBeans = PPXmlParseUtils.getInstance().parseItemIntroFile(resultString);
                            setItemIntro();
                        }else if(msg.arg1 == TECHNICIAN_DATA){
                            PreJSDataReturnBean jsDataReturnBean = GsonUtils.parseSimpleJson(resultString,
                                    PreJSDataReturnBean.class);
                            if(jsDataReturnBean.getCode() == 200){
                                preJSDataBeans = gson.fromJson(jsDataReturnBean.getData(),
                                        new TypeToken<List<PreJSDataBean>>(){}.getType());
                                //Log.i(TAG,"preJSDataBeans=" + preJSDataBeans);
                                setTechnicianList();
                            }
                        }
                        break;
                    case 2:
                        ProcessWaitingUtil.closeProcessDialog();
                        if(msg.arg2 == TECHNICIAN_ITEM){
                            CommentCustomToast.makeText(PPJSActivity.this,"ip或port插件配置出错！",Toast.LENGTH_SHORT,false).show();
                        }else if(msg.arg2 == ITEM_INTRO_FILE){
                            CommentCustomToast.makeText(PPJSActivity.this,"没有获取到配置技师类型介绍文档！",Toast.LENGTH_SHORT,false).show();
                        }
                        break;
                }
            }
        }
    };
}